package com.limf.demo.timer;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimerTest {

	public static void main(String[] args) {
		
		long now = System.currentTimeMillis();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   // 设置日期格式
		System.out.println("当前系统时间："+df.format(new Date()));
		System.out.println("当前系统时间2："+transferLongToDate("yyyy-MM-dd HH:mm:ss", now));
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 20);
		calendar.set(Calendar.MINUTE, 49);
		calendar.set(Calendar.SECOND, 0);
		
		long specTime = calendar.getTimeInMillis();
		System.out.println("specTime:"+specTime+"; now:"+now);
		
		// while循环
		// thread_while();
		
		// 方法一：使用线程的sleep方法，让线程休眠来达到按时执行的效果
		/*MyThread thread = new MyThread();
		try {
			Thread.sleep(specTime - now);
			thread.start();
		}catch(InterruptedException e) {
			e.printStackTrace();
		}*/
		
		/*
		// 方法二：使用timer.schedule来实现定时执行线程，参数如下方法执行即可
		Timer timer = new Timer();
		 // 在1秒后执行此任务，每次间隔2秒执行一次，如果传递一个Date参数，就可以在某个固定的时间执行这个任务
		timer.schedule(new MyTimerTask(), specTime-now, 2000);  
		*/
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("定时任务线程执行中...");
			}
		};
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.scheduleWithFixedDelay(runnable, 5000, 500, TimeUnit.MILLISECONDS);
		
		
	}
	
	static void thread_while() {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true) {
					System.out.println("普通线程执行中...");
					try {
						TimeUnit.SECONDS.sleep(1);
						
					}catch(InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
		});
		thread.start();
	}
	
	
	// 使用内部类，来实现线程执行后，每隔两秒继续执行一次
	static class MyThread extends Thread {
		public void run() {
			System.out.println("_________");
			MyThread thread = new MyThread();
			try {
				Thread.sleep(2000);
				thread.start();
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	// 使用内部类，利用TimerTask来实现线程的定时执行
	static class MyTimerTask extends java.util.TimerTask {
		public void run() {
			System.out.println("——————————————————————1");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("——————————————————————2");
		}
	}
	
	public static String transferLongToDate(String format, long millSec) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = new Date(millSec);
		return sdf.format(date);
	}
	
}
